import * as bcrypt from 'bcryptjs';
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@Schema({
  timestamps: true,
  toJSON: {
    transform: function (doc, ret) {
      delete ret.password;
      return ret;
    },
  },
})
export class User extends Document {
  @Prop({
    unique: true,
    sparse: true,
  })
  phone?: string;

  @Prop({
    select: false,
  })
  password: string;

  @Prop({ unique: true })
  openid?: string;

  // 密码比对方法
  comparePassword: (attempt: string) => Promise<boolean>;
}

export const UserSchema = SchemaFactory.createForClass(User);

UserSchema.methods.comparePassword = async function (
  attempt: string,
): Promise<boolean> {
  return bcrypt.compare(attempt, this.password);
};

// 密码加密中间件
UserSchema.pre<User>('save', async function (next) {
  if (!this.isModified('password')) return next();

  try {
    const salt = await bcrypt.genSalt(10);
    this.password = await bcrypt.hash(this.password, salt);
    next();
  } catch (err) {
    next(err);
  }
});
